package com.aruio.config;

import com.aruio.util.ThreadMdcUtil;
import org.slf4j.MDC;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;

import java.util.concurrent.Callable;
import java.util.concurrent.Future;

@Configuration
//@EnableScheduling
public class SchedulerConfig {

    @Bean
    public ThreadPoolTaskScheduler threadPoolTaskScheduler() {
        ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler() {
            @Override
            public Future<?> submit(Runnable task) {
                return super.submit(ThreadMdcUtil.wrap(task, MDC.getCopyOfContextMap()));
            }

            @Override
            public <T> Future<T> submit(Callable<T> task) {
                return super.submit(ThreadMdcUtil.wrap(task, MDC.getCopyOfContextMap()));
            }
        };
        scheduler.setPoolSize(5); // 设置线程池大小
        scheduler.setThreadNamePrefix("ScheduledTask-"); // 设置线程名称前缀
        scheduler.setWaitForTasksToCompleteOnShutdown(true); // 等待任务完成
        scheduler.setErrorHandler(t -> System.err.println("Error in scheduled task: " + t)); // 设置错误处理
        scheduler.initialize();
        return scheduler;
    }
}